package com.javasm.mingming.common.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * @author javasm
 * @version 0.1
 * @className EmailUtil
 * @descriptioin:
 * @date 2025/1/10 15:51
 * @since jdk11
 */
@Component
public class EmailUtil {

    Logger logger = LogManager.getLogger(EmailUtil.class);
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private MailProperties mailProperties;

    public void sendMail(String to, String title, String count, File... files){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //发件人
            helper.setFrom(mailProperties.getUsername());
            //收件人
            helper.addTo(to);
            //标题
            helper.setSubject(title);
            //内容
            helper.setText(count,true);
            //附件
            if (files != null && files.length>0){
                for (File f : files){
                    //判断传入的 是不是图片
                    if (isImage(f)){
                        helper.addInline("ei",f);
                    }
                    helper.addAttachment(f.getName(),f);
                }
            }
            //发送
            mailSender.send(message);

        } catch (MessagingException e) {
            logger.error("发送邮件异常:"+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public boolean isImage(File file){
        try {
            Image image = ImageIO.read(file);
            return image != null;
        } catch (IOException e) {
            return false;
        }
    }
}
